package com.jyw.business.obstacles.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jyw.business.obstacles.domain.ObsOrderFault;
import com.jyw.business.obstacles.domain.cache.OrderReminderCache;
import com.jyw.business.obstacles.service.IObsOrderFaultService;
import com.jyw.business.obstacles.service.IObsOrderMessageService;
import com.jyw.business.obstacles.utils.WebSocketUtils;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.vo.SysOrderReminderConfigVo;
import com.jyw.system.service.ISysOrderReminderConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 超时未派单定时任务
 */
@Component("waitDeliveryTask")
@Slf4j
public class WaitDeliveryTask {

    @Resource
    private IObsOrderFaultService orderFaultService;

    @Resource
    private ISysOrderReminderConfigService reminderConfigService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private IObsOrderMessageService obsOrderMessageService;

    /**
     * 超时未派单定时任务提醒
     */
    public void remind(){
        SysOrderReminderConfigVo config = reminderConfigService.getDefaultConfig();
        //开启了超时未派单提醒
        if(config.getDispatchTimeoutRemind()&&config.getDispatchTimeoutMinute()!=null
                &&config.getDispatchTimeoutInterval()!=null){
            log.info("运行工单超时未派单提醒");
            //读取超时几分钟
            Integer minute = config.getDispatchTimeoutMinute();
            // 间隔提醒分钟
            Integer interval = config.getDispatchTimeoutInterval();
            //计算时间,小于该时间的都属于超时
            Date timeOutDate = DateUtils.addMinutes(DateUtils.getNowDate(), -minute);
            List<ObsOrderFault> list = orderFaultService
                    .lambdaQuery()
                    .le(ObsOrderFault::getCreateTime, timeOutDate)
                    .list();
            if(CollUtil.isNotEmpty(list)){
                TimeUnit timeUnit=TimeUnit.SECONDS;
                Integer reminderSecond= interval*60;
                list.forEach(data->{
                    String orderNum = data.getOrderNum();
                    String cacheKey=CacheConstants.WAIT_DELIVERY_REMIND_KEY+orderNum;
                    String oldCache=redisCache.getCacheObject(cacheKey);
                    // 不存在缓存 发送消息
                    if(StrUtil.isEmpty(oldCache)){
                        String msg = "工单号【"+orderNum+"】派单已超时，请知晓";
                        obsOrderMessageService.sendServiceMsg(msg);
                        redisCache.setCacheObject(cacheKey, orderNum,reminderSecond, timeUnit);
                    }
                });
            }
        }
    }
}
